<?php
require(dirname(dirname(__FILE__))."/Config/config.php");
require(dirname(dirname(__FILE__))."/jssdk.php");
class chatController extends appController{
	public $wxid = 0;//数据库Id
	
	public $m;//自己的model
	public $info=array();//当前用户的微信信息
	public  function __construct(){
		parent::__construct();
	
		//基础信息构建
		
		$this->m = Model('chat');
		//微信分享参数构建
		$jsdk = $this->m ->get_jsdk();
		
		$this->assign("signPackage", $jsdk);
	
		//当前用户的微信id
		$this->wxid = $_SESSION['wxid']?$_SESSION['wxid']:0;
		
		if($this->wxid>0)
		{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$this->assign('info',$this->info);
		}
	}
	
	public function set()
	{
		$_SESSION['wxid']=$_GET['wxid'];
	}
	//清除数据
	public function clear()
	{
	
		unset($_SESSION['wxid']);
		unset($_SESSION['pid']);
		echo "已清除数据";
		exit;
	}
	//需要授权才可进入游戏
	public function canIn()
	{
		if(!$this->info)
		{
			header("Location:http://".$_SERVER['HTTP_HOST']."/ws/index.php?g=home&m=chat&a=index");
			exit;
		}
	}
	
	//微信访问地址
	public function index(){
		
		if(!isset($_SESSION['wxid']))
		{
			//是否已授权
			$this->check_member();
		}else{
			$cfg = $this->m->get_cfg();
			
			$config[c] = array('site_name' => "G4弹幕-".$cfg['site_name']);
			$this->assign_global($config);
			$this->m->updateFrontTime($cfg['frontTime']);
			//记录登陆信息
			$this->m->save_visitor($this->info['openid']);
			$result = $this->m->get_special_chat($this->wxid);
			$this->assign('rule1', json_encode($result['rule1']));//时间
			$this->assign('rule2', json_encode($result['rule2']));//条数
			$this->assign('rule3', json_encode($result['rule3']));//每日
			$this->assign('rule4', json_encode($result['rule4']));//单日
			$timestamp =intval($this->m->get_timestamp());
			$refresh = intval($this->m->get_refreshtime());
			$commentDayMax = intval($cfg['commentDayMax']);
			$commentMinuteMax = intval($cfg['commentMinuteMax']);
			$chatMaxNum = intval($cfg['chatMaxNum']);
			$staggerTime = intval($cfg['staggerTime']);
			
			//获取个人当天评论的个数
			$commentDayNum = $this->m->get_comment_num($this->wxid);
			//查询轮播图片
			$carousel = $this->m->get_indexad(18);
			$background = $this->m->get_indexad(19);
			$special_ad = $this->m->get_special_ad();
			$this->assign('specialAd',json_encode($special_ad));
			$this->assign('carouselAd',json_encode($carousel));
			$time = time();
			$this->assign('timeout',$refresh-($time-$timestamp)%$refresh);
			$this->assign('refreshtime',$refresh);
			$this->assign('commentDayMax',$commentDayMax);
			$this->assign('commentMinuteMax',$commentMinuteMax);
			$this->assign('commentDayNum',$commentDayNum);
			$this->assign('placeholder',$cfg['placeholder']);
			$this->assign('staggerTime',$staggerTime);
			$this->assign('chatMaxNum',$chatMaxNum);
			$this->assign('carousel',$carousel);
			$this->assign('background',$background[0]);
			//$num = rand(0,10);
			$this->assign("timestamp", $timestamp+intval($cfg['frontTime']));
// 			$this->assign("timestamp", $timestamp+$num);
			$this->assign("now", $time);
			$this->display('index2.html');
		}
		
	}
	
	
	/**
	 * 保存评论
	 * @return text
	 */
	public function saveComment(){
		$this->canIn();
		$data['comment'] = $_POST['text'];
		$data['wxid'] = $this->wxid;
		$data['status'] =0;
		
		$res =$this->m->create_record($data);
		print_r(json_encode($res));
// 		if($res==4004){
// 			echo "silence";
// 		}elseif ($res ==3003){
// 			echo "false";
// 		}else{
// 			echo "ok";
// 		}
	}
	
	function parseurl($url="")
	{
		$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
	
		return $url;
	}
	
	public function addClickAd(){
		$id= isset($_POST['id'])?$_POST['id']:"";
		$res = array("error"=>1);
		if($id){
			if($this->m->add_click_num($id)){
				$res['error']=0;
			}
		}
		print_r(json_encode($res));
	}
	
	public function getBox(){
		$this->canIn();
		$group_id = $_POST['group_id'];
		$res = $this->m->get_box($group_id,$this->info['wxid']);
		print_r(json_encode($res));
	}
	
	public function saveInfo(){
		$this->canIn();
		$info['phone'] =isset($_POST['phone'])?$_POST['phone']:"";
		if(preg_match("/1[3458]{1}\d{9}$/",$info['phone'])){
		
		}else{
			$res['error'] = 0;
			$res['content'] = "请填写正确的手机号码";
			die(json_encode($res));
		}
		$info['group_id'] = $_POST['group_id'];
		$info['status_id'] = isset($_POST['status_id'])?$_POST['status_id']:"";
		$info['name'] = isset($_POST['name'])?$_POST['name']:"";
		$info['addtime'] = $_SERVER['REQUEST_TIME'];
		$info['wxid'] = $this->info['wxid'];
		$res = Model('chat')->save_info($info);
		print_r(json_encode($res));
	}
	
	public function get_user_info(){
		if(!isset($_SESSION['wxid'])){
			$access_token = $this->getYaoAccessToken();
			$path = ROOT_PATH."Admin/Config/yaotv.json";
			$data = json_decode(file_get_contents($path), true);
			$appid = $data['yaoappid'];
			$user_info = $this->return_user_info($appid, $access_token, $_REQUEST['code']);
			usleep(5*100);
			if(!isset($user_info['openid'])){
				$res['error'] = 1;
				$res['content'] = "请重新登录";
				unset($_SESSION['wxid']);
				die($_REQUEST['callback']."(".json_encode($res).")");
			}
			$a = Model('app');
			$check_openid = $a->get_count_openid($user_info['openid']);
			if($check_openid == 0)
			{
				$info['openid'] = $user_info['openid'];
				$info['nickname'] = $user_info['nickname'];
				$info['sex'] = $user_info['sex'];
				$info['headimgurl'] = $user_info['headimgurl']."/64";
				$wxid =$a->insert_into_wxuser($info);
				if(!$wxid)
				{
					echo "System Error! Please wait for a while!";
				}
			}
			else
			{
				$wxid = $a->get_wxid($user_info['openid']);
			}
			$_SESSION['wxid'] = $wxid;
			//当前用户的微信信息
			$this->info = $this->m->get_record($wxid);
			$res['error'] = 0;
			$res['result'] = $this->info;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}else{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$res['error'] = 0;
			$res['result'] = $this->info;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
	}
	
	public function get_user_info2(){
		if(!isset($_SESSION['wxid'])){
			$access_token = $this->getYaoAccessToken();
			$path = ROOT_PATH."Admin/Config/yaotv.json";
			$data = json_decode(file_get_contents($path), true);
			$appid = $data['yaoappid'];
			$user_info = $this->return_user_info($appid, $access_token, $_REQUEST['code']);
			usleep(5*100);
			if(!isset($user_info['openid'])){
				$res['error'] = 1;
				$res['content'] = "请重新登录";
				unset($_SESSION['wxid']);
				die($_REQUEST['callback']."(".json_encode($res).")");
			}
			$a = Model('app');
			$check_openid = $a->get_count_openid($user_info['openid']);
			if($check_openid == 0)
			{
				$info['openid'] = $user_info['openid'];
				$info['nickname'] = $user_info['nickname'];
				$info['sex'] = $user_info['sex'];
				$info['headimgurl'] = $user_info['headimgurl']."/64";
				$wxid =$a->insert_into_wxuser($info);
				if(!$wxid)
				{
					echo "System Error! Please wait for a while!";
				}
			}
			else
			{
				$wxid = $a->get_wxid($user_info['openid']);
			}
			$_SESSION['wxid'] = $wxid;
			//当前用户的微信信息
			$this->info = $this->m->get_record($wxid);
			$res['error'] = 0;
			$res['result'] = $this->info;
			$hongbao_id = $this->m->get_now_hongbaoId()?intval($this->m->get_now_hongbaoId()):0;
			$res['hongbao_id'] = $hongbao_id;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}else{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$res['error'] = 0;
			$res['result'] = $this->info;
			$hongbao_id = $this->m->get_now_hongbaoId()?intval($this->m->get_now_hongbaoId()):0;
			$res['hongbao_id'] = $hongbao_id;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
	}
	
	
	public function getYaoAccessToken(){
		$path = ROOT_PATH."Qiaqia/Json/yao_access_token.json";
		$data = json_decode(file_get_contents($path), true);
		if(empty($data['access_token']) || $data['expire_time'] < yf_time()){
			
			$path2 = ROOT_PATH."Admin/Config/yaotv.json";
			$data2 = json_decode(file_get_contents($path2), true);
			$app['appid'] = $data2['yaoappid'];
			$app['appsecret'] = $data2['yaoappSecret'];
			$new_info = $this->getToken($app['appid'], $app['appsecret']);
			$info['access_token'] = $new_info['access_token'];
			$info['expire_time'] = yf_time() + 1500;
			$fp = fopen($path, "w");
			fwrite($fp, json_encode($info));
			fclose($fp);
			return $new_info['access_token'];
		}else{
			return $data['access_token'];
		}
	}
	
	public function getToken($appid,$secret){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);
		$token = json_decode($result);
		$yf_info['access_token'] = $token->access_token;
		$yf_info['expires_in'] = $token->expires_in;
		return $yf_info;
	}
	
	public function return_user_info($appid,$access_token,$code){
		$url = "https://api.weixin.qq.com/yaotv/user/userinfo?appid=".$appid."&access_token=".$access_token."&code=".$code;
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		return $arr;
	}
	
	
	public function get_index_info(){
		$res=array('error'=>1);
		if(!$this->wxid>0){
			unset($_SESSION['wxid']);
			$res['error'] = 0;
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$cfg = $this->m->get_cfg();
		$this->m->updateFrontTime($cfg['frontTime']);
		//记录登陆信息
		$this->m->save_visitor($this->info['openid']);
		$result = $this->m->get_special_chat2($this->wxid);
		$res['rule'] = $result;
		$timestamp =intval($this->m->get_timestamp());
		$refresh = intval($this->m->get_refreshtime());
		$commentDayMax = intval($cfg['commentDayMax']);
		$commentMinuteMax = intval($cfg['commentMinuteMax']);
		$chatMaxNum = intval($cfg['chatMaxNum']);
		$staggerTime = intval($cfg['staggerTime']);
			
		//获取个人当天评论的个数
		$commentDayNum = $this->m->get_comment_num($this->wxid);
		//查询轮播图片
		$carousel = $this->m->get_indexad(18);
		$background = $this->m->get_indexad(19);
		$special_ad = $this->m->get_special_ad();
		$res['specialAd'] = $special_ad;
		$res['carouselAd'] = $carousel;
		$time = time();
		$res['timeout'] = $refresh-($time-$timestamp)%$refresh;
		$res['refreshtime'] = $refresh;
		$res['commentDayMax'] = $commentDayMax;
		$res['commentMinuteMax'] = $commentMinuteMax;
		$res['commentDayNum'] = $commentDayNum;
		$res['placeholder'] = $cfg['placeholder'];
		$res['staggerTime'] = $staggerTime;
		$res['chatMaxNum'] = $chatMaxNum;
		$res['carousel'] = $carousel;
		$res['background'] = $background[0];
		$res['timestamp'] = $timestamp+intval($cfg['frontTime']);
		$res['now'] = $time;
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function get_chat_jsonp(){
		$filename = ROOT_PATH."chat.json";
		$json_string = file_get_contents($filename);
		$res = json_decode($json_string);
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
	/**
	 * 保存评论
	 * angularjs
	 * @return text
	 */
	public function saveComment2(){
		$this->canIn();
		$data['comment'] = $_REQUEST['text'];
		$data['wxid'] = $this->wxid;
		$data['status'] =0;
		$res =$this->m->create_record($data);
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	//angularjs
	public function addClickAd2(){
		$id= isset($_REQUEST['id'])?$_REQUEST['id']:"";
		$res = array("error"=>1);
		if($id){
			if($this->m->add_click_num($id)){
				$res['error']=0;
			}
		}
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	//angularjs
	public function getBox2(){
		$this->canIn();
		$group_id = $_REQUEST['group_id'];
		$res = $this->m->get_box($group_id,$this->info['wxid']);
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	//angularjs
	public function saveInfo2(){
		$this->canIn();
		$info['phone'] =isset($_REQUEST['phone'])?$_REQUEST['phone']:"";
		if(preg_match("/1[3458]{1}\d{9}$/",$info['phone'])){
	
		}else{
			$res['error'] = 0;
			$res['content'] = "请填写正确的手机号码";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$info['group_id'] = $_REQUEST['group_id'];
		$info['status_id'] = isset($_REQUEST['status_id'])?$_REQUEST['status_id']:"";
		$info['name'] = isset($_REQUEST['name'])?$_REQUEST['name']:"";
		$info['addtime'] = $_SERVER['REQUEST_TIME'];
		$info['wxid'] = $this->info['wxid'];
		$res = Model('chat')->save_info($info);
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	
	public function get_hongbao_sign(){
		$a = Model('app');
		$openid = $a->get_openid($_GET['wxid']);
		if(!$openid){
			$res['error'] = 1;
			$res['content'] = "请重新登录";
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$noncestr = hy_rand(28);
		
		$lottery_id =Model('chat')->get_luckyDraw($_GET['hongbao_id']);
		if(isset($_GET['captcha'])){//有值
			$captcha = $_GET['captcha'];
			$post_data = array(
					"captcha"=>$captcha,
					"lottery_id"=>$lottery_id,
					"noncestr"=>$noncestr,
					"userid"=>$openid,
			);
		}else{
			$post_data = array(
					"lottery_id"=>$lottery_id,
					"noncestr"=>$noncestr,
					"userid"=>$openid,
			);
		}
		$path2 = ROOT_PATH."Admin/Config/yaotv.json";
		$data2 = json_decode(file_get_contents($path2), true);
		$stringA = $this->ToUrlParams($post_data)."&key=".$data2['key'];
		$post_data['sign']=strtoupper(md5($stringA));
		$res['error'] = 0;
		$post_data['captcha'] = isset($post_data['captcha'])?$post_data['captcha']:"";
		$res['result'] = $post_data;
		print_r($_REQUEST['callback']."(".json_encode($res).")");
	}
	
// 	private function ToUrlParams($urlObj)
// 	{
// 		//sort($urlObj);
// 		$buff = "";
// 		foreach ($urlObj as $k => $v)
// 		{
// 			if($k != "sign"){
// 				$buff .= $k . "=" . $v . "&";
// 			}
// 		}
	
// 		$buff = trim($buff, "&");
// 		return $buff;
// 	}
	
	public function saveHongbaoInfo(){
		$info['wxid'] = isset($_GET['wxid'])?$_GET['wxid']:$this->wxid;
		$info['hongbao_id']  = $_GET['hongbao_id'];
		$info['addtime'] = $_SERVER['REQUEST_TIME'];
		$id = Model('chat')->insert($info,"get_hongbao_user");
	}
	
	public function get_url(){
		$index = isset($_GET['index'])?intval($_GET['index']):0;
		if($index==0){
			$res = array("error"=>1);
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
		$url = Model("chat")->get_url($index);
		if($url){
			$res = array("error"=>0,"url"=>$url);
			die($_REQUEST['callback']."(".json_encode($res).")");
		}else{
			$res = array("error"=>1);
			die($_REQUEST['callback']."(".json_encode($res).")");
		}
	}
	
	public function get_home_url(){
		$res["ad"] = Model("chat")->get_home_url();
		die($_REQUEST['callback']."(".json_encode($res).")");
	}
}